import { ref, computed } from 'vue'
import { DragOperationType, type DragOperationTypeValue } from './dragDrop'

// 拖拽统计接口
export interface DragStatistics {
  totalOperations: number
  successfulOperations: number
  failedOperations: number
  successRate: number
  totalDragTime: number
  averageDragTime: number
  fastestDrag: number
  slowestDrag: number
  totalDragDistance: number
  averageDragDistance: number
  shortestDrag: number
  longestDrag: number
  averageDragSpeed: number
  fastestSpeed: number
  slowestSpeed: number
  operationTypeCounts: Record<DragOperationTypeValue, number>
  componentTypeCounts: Record<string, number>
  hourlyDistribution: number[]
  performanceTrends: {
    fps: number[]
    memoryUsage: number[]
    renderTime: number[]
  }
  userBehavior: {
    undoCount: number
    redoCount: number
    clearHistoryCount: number
    exportCount: number
    importCount: number
  }
}

// 性能指标接口
export interface PerformanceMetrics {
  fps: number
  memoryUsage: number
  dragOperations: number
  renderTime: number
  lastUpdate: number
}

// 统计管理类
export class StatisticsManager {
  private statistics = ref<DragStatistics>({
    totalOperations: 0,
    successfulOperations: 0,
    failedOperations: 0,
    successRate: 0,
    totalDragTime: 0,
    averageDragTime: 0,
    fastestDrag: Infinity,
    slowestDrag: 0,
    totalDragDistance: 0,
    averageDragDistance: 0,
    shortestDrag: Infinity,
    longestDrag: 0,
    averageDragSpeed: 0,
    fastestSpeed: 0,
    slowestSpeed: Infinity,
    operationTypeCounts: {
      [DragOperationType.ADD]: 0,
      [DragOperationType.MOVE]: 0,
      [DragOperationType.DELETE]: 0,
      [DragOperationType.MODIFY]: 0,
      [DragOperationType.REORDER]: 0
    },
    componentTypeCounts: {},
    hourlyDistribution: new Array(24).fill(0),
    performanceTrends: {
      fps: [],
      memoryUsage: [],
      renderTime: []
    },
    userBehavior: {
      undoCount: 0,
      redoCount: 0,
      clearHistoryCount: 0,
      exportCount: 0,
      importCount: 0
    }
  })

  private performanceMetrics = ref<PerformanceMetrics>({
    fps: 0,
    memoryUsage: 0,
    dragOperations: 0,
    renderTime: 0,
    lastUpdate: Date.now()
  })

  // 获取统计数据
  getStatistics() {
    return this.statistics.value
  }

  // 获取性能指标
  getPerformanceMetrics() {
    return this.performanceMetrics.value
  }

  // 更新拖拽统计
  updateDragStatistics(operation: any) {
    const stats = this.statistics.value
    
    // 基础统计
    stats.totalOperations++
    if (operation.success !== false) {
      stats.successfulOperations++
    } else {
      stats.failedOperations++
    }
    stats.successRate = (stats.successfulOperations / stats.totalOperations) * 100

    // 时间统计
    if (operation.duration) {
      stats.totalDragTime += operation.duration
      stats.averageDragTime = stats.totalDragTime / stats.totalOperations
      stats.fastestDrag = Math.min(stats.fastestDrag, operation.duration)
      stats.slowestDrag = Math.max(stats.slowestDrag, operation.duration)
    }

    // 距离统计
    if (operation.distance) {
      stats.totalDragDistance += operation.distance
      stats.averageDragDistance = stats.totalDragDistance / stats.totalOperations
      stats.shortestDrag = Math.min(stats.shortestDrag, operation.distance)
      stats.longestDrag = Math.max(stats.longestDrag, operation.distance)
    }

    // 速度统计
    if (operation.duration && operation.distance) {
      const speed = operation.distance / operation.duration
      stats.averageDragSpeed = (stats.averageDragSpeed * (stats.totalOperations - 1) + speed) / stats.totalOperations
      stats.fastestSpeed = Math.max(stats.fastestSpeed, speed)
      stats.slowestSpeed = Math.min(stats.slowestSpeed, speed)
    }

    // 操作类型统计
    if (operation.type && stats.operationTypeCounts[operation.type] !== undefined) {
      stats.operationTypeCounts[operation.type]++
    }

    // 组件类型统计
    if (operation.component?.type) {
      const componentType = operation.component.type
      stats.componentTypeCounts[componentType] = (stats.componentTypeCounts[componentType] || 0) + 1
    }

    // 时间分布统计（按小时）
    const hour = new Date().getHours()
    stats.hourlyDistribution[hour]++

    // 性能趋势
    if (this.performanceMetrics.value.fps > 0) {
      stats.performanceTrends.fps.push(this.performanceMetrics.value.fps)
      stats.performanceTrends.memoryUsage.push(this.performanceMetrics.value.memoryUsage)
      stats.performanceTrends.renderTime.push(this.performanceMetrics.value.renderTime)
      
      // 限制趋势数据长度
      const maxTrendLength = 100
      if (stats.performanceTrends.fps.length > maxTrendLength) {
        stats.performanceTrends.fps.shift()
        stats.performanceTrends.memoryUsage.shift()
        stats.performanceTrends.renderTime.shift()
      }
    }
  }

  // 更新性能指标
  updatePerformanceMetrics(metrics: Partial<PerformanceMetrics>) {
    Object.assign(this.performanceMetrics.value, metrics, {
      lastUpdate: Date.now()
    })
  }

  // 更新用户行为统计
  updateUserBehaviorStats(action: keyof DragStatistics['userBehavior']) {
    this.statistics.value.userBehavior[action]++
  }

  // 重置统计
  resetStatistics() {
    this.statistics.value = {
      totalOperations: 0,
      successfulOperations: 0,
      failedOperations: 0,
      successRate: 0,
      totalDragTime: 0,
      averageDragTime: 0,
      fastestDrag: Infinity,
      slowestDrag: 0,
      totalDragDistance: 0,
      averageDragDistance: 0,
      shortestDrag: Infinity,
      longestDrag: 0,
      averageDragSpeed: 0,
      fastestSpeed: 0,
      slowestSpeed: Infinity,
      operationTypeCounts: {
        [DragOperationType.ADD]: 0,
        [DragOperationType.MOVE]: 0,
        [DragOperationType.DELETE]: 0,
        [DragOperationType.MODIFY]: 0,
        [DragOperationType.REORDER]: 0
      },
      componentTypeCounts: {},
      hourlyDistribution: new Array(24).fill(0),
      performanceTrends: {
        fps: [],
        memoryUsage: [],
        renderTime: []
      },
      userBehavior: {
        undoCount: 0,
        redoCount: 0,
        clearHistoryCount: 0,
        exportCount: 0,
        importCount: 0
      }
    }
  }

  // 获取统计摘要
  getStatisticsSummary() {
    const stats = this.statistics.value
    const performance = this.performanceMetrics.value
    
    return {
      basic: {
        totalOperations: stats.totalOperations,
        successfulOperations: stats.successfulOperations,
        failedOperations: stats.failedOperations,
        successRate: stats.successRate.toFixed(2) + '%'
      },
      performance: {
        currentFPS: performance.fps,
        averageDragTime: stats.averageDragTime.toFixed(2) + 'ms',
        averageDragDistance: stats.averageDragDistance.toFixed(2) + 'px',
        averageDragSpeed: stats.averageDragSpeed.toFixed(2) + 'px/ms'
      },
      trends: {
        fastestDrag: stats.fastestDrag === Infinity ? 'N/A' : stats.fastestDrag.toFixed(2) + 'ms',
        slowestDrag: stats.slowestDrag === 0 ? 'N/A' : stats.slowestDrag.toFixed(2) + 'ms',
        longestDrag: stats.longestDrag === 0 ? 'N/A' : stats.longestDrag.toFixed(2) + 'px',
        shortestDrag: stats.shortestDrag === Infinity ? 'N/A' : stats.shortestDrag.toFixed(2) + 'px'
      }
    }
  }

  // 获取简单统计摘要
  getStatisticsSummarySimple() {
    const stats = this.statistics.value
    return {
      total: stats.totalOperations,
      success: stats.successfulOperations,
      successRate: stats.successRate.toFixed(1) + '%',
      avgTime: stats.averageDragTime.toFixed(0) + 'ms',
      avgDistance: stats.averageDragDistance.toFixed(0) + 'px'
    }
  }

  // 生成统计报告
  generateStatisticsReport() {
    const stats = this.statistics.value
    const performance = this.performanceMetrics.value
    
    const report = {
      summary: {
        totalOperations: stats.totalOperations,
        successRate: stats.successRate.toFixed(2) + '%',
        averageDragTime: stats.averageDragTime.toFixed(2) + 'ms',
        averageDragDistance: stats.averageDragDistance.toFixed(2) + 'px'
      },
      performance: {
        currentFPS: performance.fps,
        performanceGrade: this.getPerformanceGrade(performance.fps),
        memoryUsage: performance.memoryUsage + 'MB',
        renderTime: performance.renderTime + 'ms'
      },
      operationTypes: stats.operationTypeCounts,
      componentTypes: stats.componentTypeCounts,
      hourlyDistribution: stats.hourlyDistribution,
      userBehavior: stats.userBehavior,
      recommendations: this.generateRecommendations(stats)
    }
    
    return report
  }

  // 生成优化建议
  generateRecommendations(stats: DragStatistics) {
    const recommendations = []
    
    // 基于成功率的建议
    if (stats.successRate < 80) {
      recommendations.push({
        type: 'warning',
        title: '操作成功率较低',
        description: `当前成功率仅为 ${stats.successRate.toFixed(1)}%，建议检查拖拽逻辑和用户操作流程`,
        priority: 'high'
      })
    }
    
    // 基于性能的建议
    if (stats.averageDragTime > 500) {
      recommendations.push({
        type: 'warning',
        title: '拖拽响应时间较长',
        description: `平均拖拽时间为 ${stats.averageDragTime.toFixed(0)}ms，建议优化拖拽算法`,
        priority: 'medium'
      })
    }
    
    // 基于操作类型的建议
    const moveCount = stats.operationTypeCounts[DragOperationType.MOVE]
    const addCount = stats.operationTypeCounts[DragOperationType.ADD]
    if (moveCount > addCount * 2) {
      recommendations.push({
        type: 'info',
        title: '移动操作频繁',
        description: '移动操作占比过高，建议优化组件布局或提供更好的初始位置',
        priority: 'low'
      })
    }
    
    // 基于用户行为的建议
    if (stats.userBehavior.undoCount > stats.totalOperations * 0.3) {
      recommendations.push({
        type: 'info',
        title: '撤销操作频繁',
        description: '撤销操作占比过高，建议优化操作流程或提供更好的操作反馈',
        priority: 'medium'
      })
    }
    
    return recommendations
  }

  // 获取性能等级
  getPerformanceGrade(fps: number): string {
    if (fps >= 55) return 'A'
    if (fps >= 45) return 'B'
    if (fps >= 30) return 'C'
    return 'D'
  }

  // 获取性能等级文本
  getPerformanceGradeText(grade: string): string {
    const gradeTexts: Record<string, string> = {
      'A': '优秀',
      'B': '良好',
      'C': '一般',
      'D': '较差'
    }
    return gradeTexts[grade] || '未知'
  }

  // 保存统计到本地存储
  saveStatisticsToStorage() {
    try {
      const data = {
        statistics: this.statistics.value,
        performanceMetrics: this.performanceMetrics.value,
        timestamp: Date.now()
      }
      localStorage.setItem('dragDropStatistics', JSON.stringify(data))
      return true
    } catch (error) {
      console.error('保存统计数据失败:', error)
      return false
    }
  }

  // 从本地存储加载统计
  loadStatisticsFromStorage(): boolean {
    try {
      const stored = localStorage.getItem('dragDropStatistics')
      if (!stored) return false
      
      const data = JSON.parse(stored)
      const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
      
      // 检查数据是否过期（7天）
      if (data.timestamp < sevenDaysAgo) {
        localStorage.removeItem('dragDropStatistics')
        return false
      }
      
      if (data.statistics) {
        this.statistics.value = data.statistics
      }
      if (data.performanceMetrics) {
        this.performanceMetrics.value = data.performanceMetrics
      }
      
      return true
    } catch (error) {
      console.error('加载统计数据失败:', error)
      return false
    }
  }

  // 导出统计数据为JSON
  exportStatistics(): string {
    const exportData = {
      statistics: this.statistics.value,
      performanceMetrics: this.performanceMetrics.value,
      exportTime: new Date().toISOString(),
      version: '1.0'
    }
    return JSON.stringify(exportData, null, 2)
  }

  // 导出统计数据为CSV
  exportStatisticsCSV(): string {
    const stats = this.statistics.value
    
    const csvRows = [
      ['指标', '值'],
      ['总操作数', stats.totalOperations],
      ['成功操作数', stats.successfulOperations],
      ['失败操作数', stats.failedOperations],
      ['成功率', stats.successRate.toFixed(2) + '%'],
      ['总拖拽时间', stats.totalDragTime + 'ms'],
      ['平均拖拽时间', stats.averageDragTime.toFixed(2) + 'ms'],
      ['最快拖拽', stats.fastestDrag === Infinity ? 'N/A' : stats.fastestDrag + 'ms'],
      ['最慢拖拽', stats.slowestDrag + 'ms'],
      ['总拖拽距离', stats.totalDragDistance + 'px'],
      ['平均拖拽距离', stats.averageDragDistance.toFixed(2) + 'px'],
      ['最短拖拽', stats.shortestDrag === Infinity ? 'N/A' : stats.shortestDrag + 'px'],
      ['最长拖拽', stats.longestDrag + 'px'],
      ['平均拖拽速度', stats.averageDragSpeed.toFixed(2) + 'px/ms'],
      ['最快速度', stats.fastestSpeed.toFixed(2) + 'px/ms'],
      ['最慢速度', stats.slowestSpeed === Infinity ? 'N/A' : stats.slowestSpeed.toFixed(2) + 'px/ms']
    ]
    
    return csvRows.map(row => row.join(',')).join('\n')
  }

  // 导出统计数据为HTML报告
  exportStatisticsHTML(): string {
    const stats = this.statistics.value
    const performance = this.performanceMetrics.value
    const report = this.generateStatisticsReport()
    
    return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽操作统计报告</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { text-align: center; margin-bottom: 30px; }
        .section { margin-bottom: 25px; }
        .section h2 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 5px; }
        .metric { display: flex; justify-content: space-between; margin: 10px 0; padding: 8px; background: #f8f9fa; border-radius: 4px; }
        .metric-label { font-weight: bold; }
        .metric-value { color: #007bff; }
        .chart { margin: 20px 0; }
        .bar { display: inline-block; background: #007bff; margin: 2px; border-radius: 2px; }
        .recommendations { margin-top: 20px; }
        .recommendation { padding: 10px; margin: 10px 0; border-radius: 4px; }
        .recommendation.warning { background: #fff3cd; border: 1px solid #ffeaa7; }
        .recommendation.info { background: #d1ecf1; border: 1px solid #bee5eb; }
        .recommendation.success { background: #d4edda; border: 1px solid #c3e6cb; }
        .footer { text-align: center; margin-top: 40px; color: #666; font-size: 12px; }
    </style>
</head>
<body>
    <div class="header">
        <h1>拖拽操作统计报告</h1>
        <p>生成时间: ${new Date().toLocaleString('zh-CN')}</p>
    </div>
    
    <div class="section">
        <h2>基础统计</h2>
        <div class="metric">
            <span class="metric-label">总操作数:</span>
            <span class="metric-value">${stats.totalOperations}</span>
        </div>
        <div class="metric">
            <span class="metric-label">成功操作数:</span>
            <span class="metric-value">${stats.successfulOperations}</span>
        </div>
        <div class="metric">
            <span class="metric-label">成功率:</span>
            <span class="metric-value">${stats.successRate.toFixed(2)}%</span>
        </div>
    </div>
    
    <div class="section">
        <h2>性能指标</h2>
        <div class="metric">
            <span class="metric-label">当前FPS:</span>
            <span class="metric-value">${performance.fps}</span>
        </div>
        <div class="metric">
            <span class="metric-label">平均拖拽时间:</span>
            <span class="metric-value">${stats.averageDragTime.toFixed(2)}ms</span>
        </div>
        <div class="metric">
            <span class="metric-label">平均拖拽距离:</span>
            <span class="metric-value">${stats.averageDragDistance.toFixed(2)}px</span>
        </div>
    </div>
    
    <div class="section">
        <h2>操作类型分布</h2>
        <div class="chart">
            ${Object.entries(stats.operationTypeCounts).map(([type, count]) => {
                const height = count > 0 ? (count / Math.max(...Object.values(stats.operationTypeCounts))) * 100 : 0
                return `<div class="bar" style="width: 60px; height: ${height}px;" title="${type}: ${count}"></div>`
            }).join('')}
        </div>
    </div>
    
    <div class="section">
        <h2>优化建议</h2>
        <div class="recommendations">
            ${report.recommendations.map(rec => `
                <div class="recommendation ${rec.type}">
                    <strong>${rec.title}</strong><br>
                    ${rec.description}<br>
                    <small>优先级: ${rec.priority}</small>
                </div>
            `).join('')}
        </div>
    </div>
    
    <div class="footer">
        <p>本报告由低代码平台自动生成</p>
    </div>
</body>
</html>
    `.trim()
  }
}

// 创建统计管理实例
export const statisticsManager = new StatisticsManager()

// 组合式函数
export function useStatisticsManager() {
  const statistics = computed(() => statisticsManager.getStatistics())
  const performanceMetrics = computed(() => statisticsManager.getPerformanceMetrics())
  const statisticsSummary = computed(() => statisticsManager.getStatisticsSummary())
  const statisticsSummarySimple = computed(() => statisticsManager.getStatisticsSummarySimple())

  return {
    statistics,
    performanceMetrics,
    statisticsSummary,
    statisticsSummarySimple,
    updateDragStatistics: statisticsManager.updateDragStatistics.bind(statisticsManager),
    updatePerformanceMetrics: statisticsManager.updatePerformanceMetrics.bind(statisticsManager),
    updateUserBehaviorStats: statisticsManager.updateUserBehaviorStats.bind(statisticsManager),
    resetStatistics: statisticsManager.resetStatistics.bind(statisticsManager),
    generateStatisticsReport: statisticsManager.generateStatisticsReport.bind(statisticsManager),
    exportStatistics: statisticsManager.exportStatistics.bind(statisticsManager),
    exportStatisticsCSV: statisticsManager.exportStatisticsCSV.bind(statisticsManager),
    exportStatisticsHTML: statisticsManager.exportStatisticsHTML.bind(statisticsManager),
    saveStatisticsToStorage: statisticsManager.saveStatisticsToStorage.bind(statisticsManager),
    loadStatisticsFromStorage: statisticsManager.loadStatisticsFromStorage.bind(statisticsManager)
  }
}
